package util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class TiledBackgroundPlaneImageCutter extends JFrame implements ActionListener
{
	public static void main(String[] args)
	{
		TiledBackgroundPlaneImageCutter tool = new TiledBackgroundPlaneImageCutter();
	}

	public TiledBackgroundPlaneImageCutter()
	{
		super("TiledBackgroundPlane Image Cutter");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(400, 300);
		setLocation(400, 300);
		setVisible(true);

		JButton b = new JButton("Selecionar Imagem");
		b.setActionCommand("SelectImage");
		b.addActionListener(this);
		add(b);
	}

	public void actionPerformed(ActionEvent e)
	{
		if (e.getActionCommand().equals("SelectImage"))
		{
			selectImage();
		}
	}

	public void selectImage()
	{
		JFileChooser fc = new JFileChooser();
		if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
		{
			try
			{
				int tileWidth = 400;
				String fn = fc.getSelectedFile().getAbsolutePath().toLowerCase();
				if (fn.endsWith(".gif") || fn.endsWith(".jpg") || fn.endsWith("png"))
				{
					fn = fn.replaceAll("gif|jpg", "png");
					BufferedImage img = ImageIO.read(fc.getSelectedFile());
					int n = img.getWidth() / tileWidth;
					for (int i = 0; i < n; i++)
					{
						String seqName = fn.replace(".", "_" + (i + 1) + ".");
						System.out.print("[" + (i + 1) + "] " + seqName + "   ");
						GraphicsConfiguration gc = img.createGraphics().getDeviceConfiguration();
						BufferedImage tmp = gc.createCompatibleImage(tileWidth, img.getHeight(), BufferedImage.TRANSLUCENT);
						Graphics2D g2d = tmp.createGraphics();
						g2d.setComposite(AlphaComposite.Src);
						g2d.drawImage(img.getSubimage(i * tileWidth, 0, tileWidth, img.getHeight()), 0, 0, null);
						g2d.dispose();
						ImageIO.write(tmp, "PNG", new File(seqName));
						System.out.println(" (Ok)");
					}
				}
			} catch (IOException ex)
			{
				throw new RuntimeException(ex);
			}
		}
	}
}
